<script setup lang="tsx">
defineOptions({
  name: "fabCommonQueryProduction"
});

import { ref, onMounted, nextTick, computed, onUnmounted } from "vue";
import { Search } from "@px-ui/icons-vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import fabBoardEchartsModelBoxItem from "@/views/common/fab/components/board/components/fabBoardEchartsModelBoxItem.vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import { getFabBoardStatusData, getFabBoardAreaData, queryFabCommonQueryWafer } from "@/api/modules/fab";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useRouter } from "vue-router";
import dayjs from "dayjs";

const router = useRouter();

const gap = 80;
const defaultHeight = 276;
const scrollbarHeight = ref<number>(defaultHeight);
const commonTableBoxRef = ref<HTMLElement | null>(null);
const title = ref<string>("生产状况");
const loading = ref<boolean>(false);
const waferCode = ref<string>("");
const paginationProps = {
  layout: "total, prev, pager, next",
  pagerCount: "5"
};

const fabAreaRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const fabCountRef = ref<InstanceType<typeof fabBoardEchartsModelBoxItem> | null>(null);
const fabAreaData = ref<Record<string, any> | null>(null);
const fabCountData = ref<Record<string, any> | null>(null);
const fabAreaTitle = ref<string>("状态统计");
const fabCountTitle = ref<string>("机台数量统计");
const tableParams = ref<{ waferCode: string }>({ waferCode: "" });
const tableData = ref<Array<any>>([]);
const tableLoading = ref<boolean>(false);
const list = ref([]);
const tableCloumns = computed(() => {
  return [
    {
      label: "Wafer Code",
      prop: "waferId",
      width: 90,
      render({ row, $index }: any) {
        list.value[$index] = row;
        const defaultStyle = () => {
          return {
            width: "100%",
            color: "var(--px-color-primary)",
            cursor: "pointer",
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap"
          };
        };
        const clickHandler = (row: any) => {
          const path = `/all/fab/provision/craft`;
          const startTime = dayjs().subtract(7, "day").startOf("date").format("YYYY-MM-DD HH:mm:ss");
          const endTime = dayjs().endOf("date").format("YYYY-MM-DD HH:mm:ss");
          const { technology = "", product = "", lot = "", waferId = "", wafer = "", parameter = "" } = list.value[$index];
          const p = { startTime, endTime, parameter };
          const query = { ...p, period: "week", technology, product, lot, waferId, wafer };
          let params = encodeURI(JSON.stringify(query));
          const { href } = router.resolve({ path, query: { params } });
          window.open(href, "_blank");
        };
        return () => (
          <div style={defaultStyle()} onClick={() => clickHandler(row)}>
            {list.value[$index].waferId}
          </div>
        );
      }
    },
    { label: "开始时间", prop: "startTime", width: 80 },
    { label: "结束时间", prop: "outTime", width: 80 },
    { label: "CycleTime", prop: "cycleTime", width: 80 }
  ];
});

const startLoading = () => {
  loading.value = true;
};

const closeLoading = () => {
  loading.value = false;
};

const waferCodeChangeHandler = () => {
  tableParams.value = { waferCode: waferCode.value };
};

const queryFabStatusDataFn = async (cb?: () => void) => {
  const params = { areaCode: null };
  fabAreaRef.value.loading = true;
  const res = await getFabBoardStatusData(params, () => {
    fabAreaRef.value.loading = false;
  });
  fabAreaData.value = res;
  cb && cb();
};

const queryPieDataFn = async (cb?: () => void) => {
  fabCountRef.value.loading = true;
  const res = await getFabBoardAreaData(null, () => {
    closeLoading();
    fabCountRef.value.loading = false;
  });
  fabCountData.value = res;
  cb && cb();
};

const init = async () => {
  startLoading();
  queryFabStatusDataFn(async () => {
    await nextTick();
    fabAreaRef.value.init(true, true);
  });
  queryPieDataFn(async () => {
    await nextTick();
    fabCountRef.value.init(true, false, true);
  });
  closeLoading();
};

onMounted(async () => {
  await init();
  await nextTick();
  await useUpdateDomHeight(scrollbarHeight, commonTableBoxRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <modelBox :title="title">
    <div v-loading="loading" class="fab-common--query-production-content">
      <div class="production-area">
        <fabBoardEchartsModelBoxItem ref="fabAreaRef" echartsType="pie" unit="台" :name="fabAreaTitle" :data="fabAreaData" />
      </div>
      <div class="production-count">
        <fabBoardEchartsModelBoxItem ref="fabCountRef" echartsType="pie" unit="台" :name="fabCountTitle" :data="fabCountData" />
      </div>
      <div class="production-wafer">
        <div class="production-wafer-head">
          <div class="production-wafer-head-label">跑片记录</div>
          <div class="production-wafer-head-input">
            <px-input
              v-model.trim="waferCode"
              clearable
              :prefix-icon="Search"
              size="small"
              placeholder="请输入Wafer Code"
              @keydown.enter="waferCodeChangeHandler"
              @clear="waferCodeChangeHandler"
            />
          </div>
        </div>
        <div v-show="!!tableData?.length" ref="commonTableBoxRef" class="production-wafer-table">
          <commonTable
            ref="commonTableRef"
            v-model="tableData"
            v-model:loading="tableLoading"
            mode="stripe"
            immediate
            :border="false"
            :tableCloumns="tableCloumns"
            :height="scrollbarHeight"
            :paginationProps="paginationProps"
            :axiosApi="queryFabCommonQueryWafer"
            :params="tableParams"
          />
        </div>
        <div v-if="!tableData?.length" v-loading="tableLoading" class="production-wafer-table-empty">
          <px-empty class="px-empty-common" />
        </div>
      </div>
    </div>
  </modelBox>
</template>

<style lang="scss" scoped>
.fab-common--query-production-content {
  display: grid;
  grid-template-rows: repeat(3, 33.33%);
  grid-template-columns: repeat(2, 50%);
  gap: 8px;
  width: calc(100% - 8px);
  height: calc(100% - 8px);

  .production-area {
    grid-area: 1 / 1 / 2 / 2;
  }

  .production-count {
    grid-area: 1 / 2 / 2 / 3;
  }

  .production-wafer {
    grid-area: 2 / 1 / 4 / 3;
    display: flex;
    flex-direction: column;
    .production-wafer-head {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 36px;
      padding: 0 8px;
      // background-color: #f5f5f5;

      .production-wafer-head-label {
        font-size: 14px;
        font-weight: 600;
        color: #222;
      }

      .production-wafer-head-input {
        width: 160px;
      }
    }

    .production-wafer-table {
      width: 100%;
    }
    .production-wafer-table-empty {
      flex: 1;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
